package com.crm.jpaandthymeleaf.config.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.crm.jpaandthymeleaf.entity.SysRight;
import com.crm.jpaandthymeleaf.service.ISysRightService;
import com.crm.jpaandthymeleaf.service.ISysRoleService;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 周敬
 * @version 1.0
 * @packageName com.crm.jpaandthymeleaf.config.shiro
 * @fileName ShiroConfig
 * @createTime 2021/12/24-8:50-星期五
 * @lastModify 2021/12/24-8:50-星期五
 */

@Configuration
public class ShiroConfig {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.timeout}")
    private int timeout;
    @Value("${redis.hash.algorithm}")
    private String hashAlgorithm;
    @Value("${redis.hash.count}")
    private int hashCount;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysRightService sysRightService;


    /**
     * 开启Shiro注解
     * 需借助SpringAOP扫描使用Shiro注解的类，并在必要时进行安全逻辑验证
     * 配置以下两个bean（DefaultAdvisorAutoProxyCreator和 AuthorizationAttributeSourceAdvisor）
     * @return
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){

        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        advisorAutoProxyCreator.setProxyTargetClass(true);
        return advisorAutoProxyCreator;
    }

    /**
     * 开启AOP注解的支持
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    /**
     * Redis管理器，用于管理Redis连接
     * @return
     */
    public RedisManager redisManager(){
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(host);
        //没密码需要注释
//        redisManager.setPassword(password);
        redisManager.setPort(port);
        redisManager.setTimeout(timeout);
        return redisManager;
    }

    /**
     * Redis缓存管理
     * @return
     */
    public RedisCacheManager cacheManager(){
        RedisCacheManager cacheManager = new RedisCacheManager();
        cacheManager.setRedisManager(redisManager());
        //缓存名称
        cacheManager.setPrincipalIdFieldName("usrName");
        //缓存有效时间 1800 = 30分钟
        cacheManager.setExpire(1800);
        return cacheManager;
    }

    /**
     * 使用Redis做Session数据持久化
     * @return
     */
    public RedisSessionDAO redisSessionDAO(){
        RedisSessionDAO sessionDAO = new RedisSessionDAO();
        sessionDAO.setRedisManager(redisManager());
        return sessionDAO;
    }

    /**
     * 会话管理
     * @return
     */
    public DefaultWebSessionManager sessionManager(){
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setSessionDAO(redisSessionDAO());
        return sessionManager;
    }

    /**
     * 凭证匹配器
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //使用md5算法进行加密
        hashedCredentialsMatcher.setHashAlgorithmName(hashAlgorithm);
        //设置散列次数，意为加密几次
        hashedCredentialsMatcher.setHashIterations(hashCount);
        return hashedCredentialsMatcher;
    }

    /**
     * 自定义Realm
     * @return
     */
    @Bean
    public MyShiroRealm myShiroRealm(){
        MyShiroRealm shiroRealm = new MyShiroRealm();
        //设置驱动缓存，并设置缓存名称
        shiroRealm.setCachingEnabled(true);
        shiroRealm.setAuthorizationCachingEnabled(true);
        shiroRealm.setAuthorizationCacheName("authorizationCache");
        //设置密码凭证
        shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return shiroRealm;
    }

    /**
     * 安全管理器SecurityManager
     * @return
     */
    @Bean
    public SecurityManager securityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //注入Realm
        securityManager.setRealm(myShiroRealm());
        //注入缓存管理器
        securityManager.setCacheManager(cacheManager());
        //注入会话管理器
        securityManager.setSessionManager(sessionManager());
        return securityManager;
    }

    /**
     * thymeleaf页面上使用shiro标签
     * @return
     */
    @Bean(name = "shiroDialect")
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }

    /**
     * Shiro过滤器，权限验证
     * @param securityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactory = new ShiroFilterFactoryBean();

        //注入securityManager
        shiroFilterFactory.setSecurityManager(securityManager);

        //权限验证，使用Filter的控制资源（URL）的访问
        //当前用户没进行登录时，进入login页面
        shiroFilterFactory.setLoginUrl("/login");
        //当用户登录成功后，进入index页面
        shiroFilterFactory.setSuccessUrl("/index");
        //没有权限跳转403页面
        shiroFilterFactory.setUnauthorizedUrl("/403");

        //必须使用LinkedHashMap（有序集合）
        //所有的拦截规则
        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();

        //配置可以匿名访问的资源（URL）：静态资源  anon = 匿名
        filterChainDefinitionMap.put("/css/**","anon");
        filterChainDefinitionMap.put("/fonts/**","anon");
        filterChainDefinitionMap.put("/images/**","anon");
        filterChainDefinitionMap.put("/js/**","anon");
        filterChainDefinitionMap.put("/localcss/**","anon");
        filterChainDefinitionMap.put("/localjs/**","anon");
        filterChainDefinitionMap.put("/login","anon");

        filterChainDefinitionMap.put("/doLogin","anon");
        filterChainDefinitionMap.put("/api/doLogin","anon");
        //注销过滤器，shiro会自己退出登录
        filterChainDefinitionMap.put("/logout","logout");

        //配置需要特定权限才能访问的资源
        //静态授权，包括全部需要特定权限才能访问的资源（URL）
//        filterChainDefinitionMap.put("/user/list","perms[用户列表]");
//        filterChainDefinitionMap.put("/user/add","perms[用户添加]");
//        filterChainDefinitionMap.put("/user/edit","perms[用户编辑]");
//        filterChainDefinitionMap.put("/user/del","perms[用户删除]");
        //....

        List<SysRight> allSysRight = sysRightService.findRightAll();
        for (SysRight right : allSysRight) {
            if(StringUtils.hasText(right.getRightUrl())){
                System.out.println("要访问【" + right.getRightUrl() + "】连接，必有要有【" + right.getRightText() + "】权限");
                filterChainDefinitionMap.put(right.getRightUrl(),"perms["+right.getRightText()+"]");
            }
        }

        //配置认证访问，其他资源（URL）必须认证通过才能访问  authc = 认证
        //必须放在过滤器链的最后面
        filterChainDefinitionMap.put("/**","authc");
        shiroFilterFactory.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactory;
    }




}
